﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.DataAccess;
using YiYiTong.Rocket.Model.Manager;
using YiYiTong.Rocket.Model.ParamModel;
using YiYiTong.Rocket.EFDBFirst;
using System.Web;
using System.IO;
using OfficeOpenXml;
using YiYiTong.Rocket.Model.ParamModel.Product;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.Business.Biz;

namespace YiYiTong.Rocket.Business
{
    public class TempProductBiz
    {
        #region Instance
        private TempProductBiz()
        {
        }
        private static TempProductBiz _instance;

        private static object _syncObject = new object();

        public static TempProductBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new TempProductBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion


        /// <summary>
        /// 上传压缩文件
        /// </summary>
        /// <param name="aDZ_GoodsTempZip"></param>
        /// <returns></returns>
        public Tuple<bool, string> addMoreTempProduct(ADZ_GoodsTempZip aDZ_GoodsTempZip)
        {
            StringBuilder strb = new StringBuilder();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ///以下添加新图片
            HttpFileCollection hfc = HttpContext.Current.Request.Files;
            if (hfc != null && hfc.Count > 0)
            {
                bool needSave = true;
                for (int i = 0; i < hfc.Count; i++)
                {
                    needSave = true;
                    var file = hfc[i];
                    if (file == null || string.IsNullOrWhiteSpace(file.FileName))
                        continue;
                    try
                    {
                        var contentType = file.ContentType;
                        var len = file.ContentLength;
                        //var fileType = new string[] { "application/zip", };
                        //if (!fileType.Any(b => b.Contains(contentType)))
                        //{
                        //    strb.Append($"_{file.FileName}只能上传{string.Join(",", fileType)}格式的文件。");
                        //    continue;
                        //}

                        if (len > 1024 * 1024 * 100)
                        {
                            strb.Append($"_{file.FileName}上传文件大小只能在100M以下。");
                            continue;
                        }

                        var zip_temp_dir = ConfigHelper.AppSetting<string>("zip_temp_dir", "~/upload/zip");
                        zip_temp_dir = HttpContext.Current.Server.MapPath(zip_temp_dir);

                        string fileName = file.FileName;

                        if (dbcontext.ADZ_GoodsTempZip.FirstOrDefault(t => (t.file_name == fileName) && t.status > 0) != null)
                        {
                            needSave = false;
                            strb.Append($"_{file.FileName}文件已经存在。");
                        }
                        if (dbcontext.ADZ_GoodsTempZip.FirstOrDefault(t => (t.batch == aDZ_GoodsTempZip.batch) && t.status > 0) != null)
                        {
                            needSave = false;
                            strb.Append($"_{aDZ_GoodsTempZip.batch}批次已经存在。");
                        }

                        if (needSave)
                        {
                            string file_fullpath = Path.Combine(zip_temp_dir, fileName);
                            string file_dir = Path.GetDirectoryName(file_fullpath);
                            if (!Directory.Exists(file_dir))
                                Directory.CreateDirectory(file_dir);
                            try
                            {
                                file.SaveAs(file_fullpath);
                                dbcontext.ADZ_GoodsTempZip.Add(
                                    new ADZ_GoodsTempZip
                                    {
                                        file_name = fileName,
                                        status = 1,
                                        remark = "文件上传成功",
                                        create_time = DateTime.Now,
                                        batch = aDZ_GoodsTempZip.batch
                                    }
                                    );
                            }
                            catch (Exception ex)
                            {
                                dbcontext.ADZ_GoodsTempZip.Add(
                                    new ADZ_GoodsTempZip
                                    {
                                        file_name = fileName,
                                        status = 0,
                                        remark = "文件上传失败",
                                        create_time = DateTime.Now,
                                        batch = aDZ_GoodsTempZip.batch
                                    }
                                    );
                            }
                            finally
                            {
                                dbcontext.SaveChanges();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        strb.Append($"_{file.FileName}异常:" + ex.GetExcetionMessage());
                    }
                }
            }
            if (strb.Length > 0)
                return new Tuple<bool, string>(false, strb.ToString());
            else
                return new Tuple<bool, string>(true, "文件上传成功");
        }
        /// <summary>
        /// 解压缩zip并导入数据
        /// </summary>
        /// <param name="aDZ_GoodsTempZip"></param>
        /// <returns></returns>
        public Tuple<bool, string, List<string>> unZipMoreTempProduct(long id)
        {
            List<string> excel_path = new List<string>();
            int succcount = 0;
            int failcount = 0;
            StringBuilder strb = new StringBuilder();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ADZ_GoodsTempZip aDZ_GoodsTempZip = dbcontext.ADZ_GoodsTempZip.FirstOrDefault(t => t.seq_id == id);
            if (aDZ_GoodsTempZip == null)
            {
                return new Tuple<bool, string, List<string>>(false, $"解压的id[{id}]不存在", excel_path);
            }
            if (aDZ_GoodsTempZip.status != 1)
            {
                return new Tuple<bool, string, List<string>>(false, $"解压的id[{id}]状态错误[{aDZ_GoodsTempZip.file_name}][{aDZ_GoodsTempZip.status}]", excel_path);
            }
            var zip_temp_dir = ConfigHelper.AppSetting<string>("zip_temp_dir", "~/upload/zip");
            zip_temp_dir = HttpContext.Current.Server.MapPath(zip_temp_dir);

            string fileName = aDZ_GoodsTempZip.file_name;
            string file_fullpath = Path.Combine(zip_temp_dir, fileName);
            string unzip_filepath = "";
            var unzip_result = ZipHelper.UnZip(file_fullpath, unzip_filepath);
            try
            {
                if (!unzip_result.Item1)
                {
                    strb.Append(unzip_result.Item2);
                }
                else
                {
                    aDZ_GoodsTempZip.status = 2;

                    dbcontext.SaveChanges();


                    Dictionary<string, string> labelDicNameType = ReleaseBiz.GetLabelNameTypeDic();

                    if (unzip_result.Item3.Count > 0)
                    {
                        bool contain_excel = false;

                        foreach (var item in unzip_result.Item3)
                        {
                            try
                            {
                                FileInfo file = new FileInfo(item);
                                if (FileHelper.CheckIsExcel(file.Extension))
                                {
                                    excel_path.Add(item);
                                    List<AddTempProductModel> tempModelList = new List<AddTempProductModel>();

                                    DataTable table1 = new DataTable();
                                    contain_excel = true;
                                    using (ExcelPackage package = new ExcelPackage(file))
                                    {
                                        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                                        int rowCount = worksheet.Dimension.Rows;
                                        int colCount = worksheet.Dimension.Columns;
                                        int start_row = 1 + 1;
                                        int start_col = 0 + 1;

                                        for (int col = start_col; col <= colCount; col++)
                                        {
                                            int row = 1;
                                            string colName = StringHelper.GetText(worksheet.Cells[row, col].Value);
                                            string colProperty = "";
                                            if (!string.IsNullOrWhiteSpace(colName))
                                            {
                                                bool isok = UploadExcelModel.TableDic.TryGetValue(colName, out colProperty);
                                                if (isok)
                                                {
                                                    table1.Columns.Add(colProperty);
                                                }
                                                else
                                                {
                                                    strb.Append($"表头[{colName}]未配置，");
                                                }
                                            }
                                            else
                                            {
                                                strb.Append($"表头[{row}，{col}]不能空着，");
                                            }
                                        }
                                        if (strb.Length > 0)
                                        {
                                            aDZ_GoodsTempZip.remark = strb.ToString();
                                            dbcontext.SaveChanges();
                                            return new Tuple<bool, string, List<string>>(false, strb.ToString(), excel_path);
                                        }

                                        for (int row = start_row; row <= rowCount; row++)
                                        {
                                            var rowtext = StringHelper.GetText(worksheet.Cells[row, 1].Value);
                                            if (rowtext == "说明：")
                                            {
                                                break;
                                            }
                                            //第一列和第二列都没数据表示结束
                                            if (worksheet.Cells[row, 1].Value == null
                                                &&
                                                worksheet.Cells[row, 2].Value == null
                                                )
                                            {
                                                break;
                                            }

                                            DataRow dr = table1.NewRow();
                                            for (int col = start_col; col <= colCount; col++)
                                            {
                                                var content = StringHelper.GetText(worksheet.Cells[row, col].Text);
                                                if (table1.Columns[col - 1].ColumnName == "label_type")
                                                {
                                                    //label_type 需要转义
                                                    string str_label_type = "";
                                                    if (labelDicNameType.TryGetValue(content, out str_label_type))
                                                        dr[col - 1] = int.Parse(str_label_type);
                                                }
                                                else if (table1.Columns[col - 1].ColumnName == "currency_type")
                                                {
                                                    dr[col - 1] = (int)(EnumHelper.ParseByDescription<CurrencyType>(content, false));
                                                }
                                                else if (table1.Columns[col - 1].ColumnName == "show_min_level")
                                                {
                                                    if (content == "可看")
                                                        dr[col - 1] = 0;
                                                    else
                                                        dr[col - 1] = 1;
                                                }
                                                else if (table1.Columns[col - 1].ColumnName == "include_tax")
                                                {
                                                    dr[col - 1] = (int)(EnumHelper.ParseByDescription<include_tax>(content, false));
                                                }
                                                else
                                                {
                                                    dr[col - 1] = content;
                                                }
                                            }
                                            table1.Rows.Add(dr);
                                        }
                                    }
                                    if (table1.Rows.Count > 0)
                                    {
                                        string jsonData2 = JsonHelper.Serialize(table1);

                                        int rowCounts = table1.Rows.Count;

                                        var aDZ_GoodsMaster = JsonHelper.Deserialize<List<ADZ_GoodsMaster>>(jsonData2);
                                        var aDZ_GoodsCategory = JsonHelper.Deserialize<List<ADZ_GoodsCategory>>(jsonData2);
                                        var aDZ_BrandMaster = JsonHelper.Deserialize<List<ADZ_BrandMaster>>(jsonData2);
                                        var aDZ_GoodsLabel = JsonHelper.Deserialize<List<ADZ_GoodsLabel>>(jsonData2);
                                        var aDZ_SupplierMaster = JsonHelper.Deserialize<List<ADZ_SupplierMaster>>(jsonData2);
                                        var aDZ_MaterialSource = JsonHelper.Deserialize<List<ADZ_SupplierMaster>>(jsonData2);
                                        //根据业务的额外信息
                                        var goodsBusinessModel = JsonHelper.Deserialize<List<GoodsBusinessModel>>(jsonData2);
                                        using (ExcelPackage package = new ExcelPackage(file))
                                        {
                                            ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                                            int rowCount = worksheet.Dimension.Rows;
                                            int colCount = worksheet.Dimension.Columns;

                                            for (int index = 0; index < rowCounts; index++)
                                            {
                                                var tempModel = new AddTempProductModel()
                                                {
                                                    aDZ_GoodsMaster = aDZ_GoodsMaster[index],
                                                    aDZ_GoodsCategory = aDZ_GoodsCategory[index],
                                                    aDZ_BrandMaster = aDZ_BrandMaster[index],
                                                    aDZ_GoodsLabel = aDZ_GoodsLabel[index],
                                                    aDZ_SupplierMaster = aDZ_SupplierMaster[index],
                                                    aDZ_MaterialSource = aDZ_MaterialSource[index],
                                                    zip_id = id,
                                                    goodsBusinessModel = goodsBusinessModel[index]
                                                };
                                                tempModel.aDZ_MaterialSource.supplier_name = tempModel.aDZ_MaterialSource.material_name;

                                                DataRow dataRow = table1.Rows[index];

                                                foreach (var imgurl in unzip_result.Item3)
                                                {
                                                    var file_extens = Path.GetExtension(imgurl);
                                                    if (FileHelper.CheckIsImg(file_extens))
                                                    {
                                                        var filtName_imgName = Path.GetFileNameWithoutExtension(imgurl);
                                                        if (dataRow["img_name"] != null && filtName_imgName.StartsWith(dataRow["img_name"].ToString() + "_"))
                                                        {
                                                            string key = $"img/{Path.GetFileNameWithoutExtension(file.Name)}_{Path.GetFileName(imgurl)}";
                                                            var putImgRet = AliyunOssBiz.PutGoodsImgDir(key, imgurl);
                                                            if (putImgRet.Item1)
                                                            {
                                                                tempModel.aDZ_GoodsIMGs.Add(
                                                                    new ADZ_GoodsIMG
                                                                    {
                                                                        create_time = DateTime.Now,
                                                                        img_url = key,
                                                                        sort_NO = 10
                                                                    }
                                                                    );
                                                            }
                                                        }
                                                    }
                                                }
                                                var addresult = addTempProductZip(tempModel);
                                                if (addresult.Item1)
                                                {
                                                    succcount++;
                                                }
                                                else
                                                {
                                                    worksheet.Cells[index + 2, colCount].Value = addresult.Item2;
                                                    strb.Append(addresult.Item2);
                                                    failcount++;
                                                }
                                            }
                                            string error_path = Path.Combine("/", "upload", "error");
                                            string error_local_path = HttpContext.Current.Server.MapPath(error_path);
                                            string error_file_name = DateTime.Now.ToString(5) + "_" + file.Name;
                                            if (!Directory.Exists(error_local_path))
                                            {
                                                Directory.CreateDirectory(error_local_path);
                                            }
                                            error_local_path = Path.Combine(error_local_path, error_file_name);
                                            package.SaveAs(new FileInfo(error_local_path));
                                            aDZ_GoodsTempZip.error_path += Path.Combine(error_path, error_file_name) + ";";
                                            excel_path.Add(Path.Combine(error_path, error_file_name));
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                string msg = $"{item}_{ex.GetExcetionMessage()}";
                                strb.Append(msg);
                                LogHelper.Error($"msg");
                            }
                        }
                        if (!contain_excel)
                        {
                            string msg = $"压缩包[{fileName}]里没有Excel文件";
                            strb.Append(msg);
                            aDZ_GoodsTempZip.remark = strb.ToString();
                            dbcontext.SaveChanges();
                            return new Tuple<bool, string, List<string>>(false, msg, excel_path);
                        }
                    }
                }
            }
            catch (Exception exx)
            {
                string msg = $"{exx.GetExcetionMessage()}";
                strb.Append(msg);
            }
            var unzip_bool = false;
            if (strb.Length == 0)
            {
                unzip_bool = true;
                strb.Append("全部解压成功");
            }
            if (succcount > 0)
            {
                unzip_bool = true;
            }

            aDZ_GoodsTempZip.remark = strb.ToString();

            if (succcount > 0)
                aDZ_GoodsTempZip.remark = $"成功{succcount}条 " + aDZ_GoodsTempZip.remark;
            if (failcount > 0)
                aDZ_GoodsTempZip.remark = $"失败{failcount}条 " + aDZ_GoodsTempZip.remark;

            dbcontext.SaveChanges();
            return new Tuple<bool, string, List<string>>(unzip_bool, aDZ_GoodsTempZip.remark, excel_path);
        }

        /// <summary>
        /// 将解压出来的数据入库
        /// </summary>
        /// <param name="paramModel"></param>
        /// <returns></returns>
        public Tuple<bool, string, ADZ_GoodsTemp> addTempProductZip(AddTempProductModel paramModel)
        {

            ////使用name上传
            StringBuilder strb = new StringBuilder();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var checkResult = paramModel.CheckAdd();
            if (!checkResult.Item1)//参数校验失败
            {
                strb.Append(checkResult.Item2);
            }

            var supplier = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == paramModel.aDZ_SupplierMaster.supplier_name);
            if (supplier == null)
                strb.Append($"供应商【{paramModel.aDZ_SupplierMaster.supplier_name}】不存在，");
            else
            {
                paramModel.aDZ_SupplierMaster = supplier;
                paramModel.aDZ_GoodsMaster.supplier_id = supplier.supplier_id;
            }

            //新增物料来源
            var material_source = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == paramModel.aDZ_MaterialSource.supplier_name);
            if (material_source == null)
                strb.Append($"物料来源【{paramModel.aDZ_MaterialSource.supplier_name}】不存在，");
            else
            {
                paramModel.aDZ_MaterialSource = material_source;
                paramModel.aDZ_GoodsMaster.material_source = material_source.supplier_id;
            }

            var brand = dbcontext.ADZ_BrandMaster.FirstOrDefault(t => t.brand_name == paramModel.aDZ_BrandMaster.brand_name);
            if (brand == null)
                strb.Append($"品牌【{paramModel.aDZ_BrandMaster.brand_name}】不存在，");
            else
            {
                brand.brand_content = "";
                paramModel.aDZ_BrandMaster = brand;
                paramModel.aDZ_GoodsMaster.brand_id = brand.brand_id;
            }

            var category = dbcontext.ADZ_GoodsCategory.FirstOrDefault(t => t.category_name == paramModel.aDZ_GoodsCategory.category_name);
            if (category == null)
                strb.Append($"分类【{paramModel.aDZ_GoodsCategory.category_name}】不存在，");
            else
            {
                paramModel.aDZ_GoodsCategory = category;
                paramModel.aDZ_GoodsMaster.category_id = category.category_id;
            }

            ///最小出库量等于库存量
            if (!(paramModel.aDZ_GoodsMaster.min_amount > 0))
            {
                paramModel.aDZ_GoodsMaster.min_amount = paramModel.aDZ_GoodsMaster.stock_amount;
            }
            //最小可见会员等级默认为1
            if (!paramModel.aDZ_GoodsLabel.show_min_level.HasValue)
            {
                paramModel.aDZ_GoodsLabel.show_min_level = 1;
            }

            ///设置首图
            paramModel.aDZ_GoodsIMGs.ForEach(t =>
            {
                if (t.img_url.Contains("_1."))
                    t.sort_NO = 1;
            });



            ADZ_GoodsTemp aDZ_GoodsTemp = new ADZ_GoodsTemp();
            aDZ_GoodsTemp.create_time = DateTime.Now;
            aDZ_GoodsTemp.MPN = paramModel.aDZ_GoodsMaster.MPN;
            aDZ_GoodsTemp.label_type = paramModel.aDZ_GoodsLabel.label_type;
            aDZ_GoodsTemp.data_json = JsonHelper.Serialize(paramModel);
            aDZ_GoodsTemp.update_time = DateTime.Now;
            if (strb.Length > 0)
            {
                aDZ_GoodsTemp.status = 0;
                strb.Append("操作失败");
                return new Tuple<bool, string, ADZ_GoodsTemp>(false, strb.ToString(), aDZ_GoodsTemp);
            }
            else
                aDZ_GoodsTemp.status = 1;
            aDZ_GoodsTemp.remark = strb.ToString();
            aDZ_GoodsTemp.zip_id = paramModel.zip_id;
            ADZ_GoodsTemp result_aDZ_GoodsTemp = dbcontext.ADZ_GoodsTemp.Add(aDZ_GoodsTemp);

            dbcontext.SaveChanges();

            if (result_aDZ_GoodsTemp.seq_id > 0)
            {
                strb.Append("操作成功");
                return new Tuple<bool, string, ADZ_GoodsTemp>(true, strb.ToString(), result_aDZ_GoodsTemp);
            }
            else
            {
                strb.Append("操作失败");
                return new Tuple<bool, string, ADZ_GoodsTemp>(false, strb.ToString(), result_aDZ_GoodsTemp);
            }
        }



        /// <summary>
        /// 通过参数添加待上架商品
        /// </summary>
        /// <param name="paramModel"></param>
        /// <returns></returns>
        public Tuple<bool, string, ADZ_GoodsTemp> addTempProduct(AddTempProductModel paramModel)
        {
            var checkResult = paramModel.CheckAdd();
            if (!checkResult.Item1)//参数校验失败
            {
                return new Tuple<bool, string, ADZ_GoodsTemp>(checkResult.Item1, checkResult.Item2, null);
            }

            ////使用name上传
            StringBuilder strb = new StringBuilder();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var supplier = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == paramModel.aDZ_SupplierMaster.supplier_name);
            if (supplier == null)
                strb.Append($"供应商【{paramModel.aDZ_SupplierMaster.supplier_name}】不存在，");
            else
            {
                paramModel.aDZ_SupplierMaster = supplier;
                paramModel.aDZ_GoodsMaster.supplier_id = supplier.supplier_id;
            }

            //新增物料来源
            var material_source = dbcontext.ADZ_SupplierMaster.FirstOrDefault(t => t.supplier_name == paramModel.aDZ_MaterialSource.supplier_name);
            if (material_source == null)
                strb.Append($"物料来源【{paramModel.aDZ_MaterialSource.supplier_name}】不存在，");
            else
            {
                paramModel.aDZ_MaterialSource = material_source;
                paramModel.aDZ_GoodsMaster.material_source = material_source.supplier_id;
            }


            var brand = dbcontext.ADZ_BrandMaster.FirstOrDefault(t => t.brand_name == paramModel.aDZ_BrandMaster.brand_name);
            if (brand == null)
                strb.Append($"品牌【{paramModel.aDZ_BrandMaster.brand_name}】不存在，");
            else
            {
                brand.brand_content = "";
                paramModel.aDZ_BrandMaster = brand;
                paramModel.aDZ_GoodsMaster.brand_id = brand.brand_id;
            }

            var category = dbcontext.ADZ_GoodsCategory.FirstOrDefault(t => t.category_name == paramModel.aDZ_GoodsCategory.category_name);
            if (category == null)
                strb.Append($"分类【{paramModel.aDZ_GoodsCategory.category_name}】不存在，");
            else
            {
                paramModel.aDZ_GoodsCategory = category;
                paramModel.aDZ_GoodsMaster.category_id = category.category_id;
            }

            if (strb.Length > 0)
            {
                return new Tuple<bool, string, ADZ_GoodsTemp>(false, strb.ToString(), null);
            }


            //移除删掉的图片
            for (int i = paramModel.aDZ_GoodsIMGs.Count - 1; i >= 0; i--)
            {
                var item = paramModel.aDZ_GoodsIMGs[i];
                if (string.IsNullOrWhiteSpace(item.img_url))
                    paramModel.aDZ_GoodsIMGs.Remove(item);
            }

            ///设置首图
            paramModel.aDZ_GoodsIMGs.ForEach(t =>
            {
                if (t.img_url == paramModel.first_img)
                    t.sort_NO = 1;
                else
                    t.sort_NO = 10;
            });

            ///以下添加新图片
            HttpFileCollection hfc = HttpContext.Current.Request.Files;
            if (hfc != null && hfc.Count > 0)
            {
                for (int i = 0; i < hfc.Count; i++)
                {
                    var file = hfc[i];
                    var putResult = ImageFileBiz.UpImg(file);
                    if (!putResult.Item1)
                    {
                        strb.Append(putResult.Item2);
                    }
                    else
                    {
                        var sort_NO = 10;
                        if (paramModel.first_img == file.FileName)
                        {
                            sort_NO = 1;
                        }
                        ADZ_GoodsIMG goodsImg = new ADZ_GoodsIMG()
                        {
                            create_time = DateTime.Now,
                            img_type = 1,
                            img_url = putResult.Item3,
                            sort_NO = sort_NO
                        };
                        paramModel.aDZ_GoodsIMGs.Add(goodsImg);
                    }
                }
            }





            ADZ_GoodsTemp aDZ_GoodsTemp = null;
            if (paramModel.aDZ_GoodsTemp.seq_id > 0)
            {
                aDZ_GoodsTemp = dbcontext.ADZ_GoodsTemp.FirstOrDefault(t => t.seq_id == paramModel.aDZ_GoodsTemp.seq_id);
            }
            if (aDZ_GoodsTemp == null)
            {
                aDZ_GoodsTemp = new ADZ_GoodsTemp();
                aDZ_GoodsTemp.create_time = DateTime.Now;
            }

            aDZ_GoodsTemp.MPN = paramModel.aDZ_GoodsMaster.MPN;
            aDZ_GoodsTemp.label_type = paramModel.aDZ_GoodsLabel.label_type;
            aDZ_GoodsTemp.data_json = JsonHelper.Serialize(paramModel);
            aDZ_GoodsTemp.status = 1;
            aDZ_GoodsTemp.update_time = DateTime.Now;
            aDZ_GoodsTemp.remark = paramModel.aDZ_GoodsTemp.remark + strb.ToString();

            ADZ_GoodsTemp result_aDZ_GoodsTemp = aDZ_GoodsTemp;
            if (aDZ_GoodsTemp.seq_id <= 0)
                result_aDZ_GoodsTemp = dbcontext.ADZ_GoodsTemp.Add(aDZ_GoodsTemp);

            if (paramModel.aDZ_GoodsMaster.min_amount == 0)
                paramModel.aDZ_GoodsMaster.min_amount = paramModel.aDZ_GoodsMaster.stock_amount;

            dbcontext.SaveChanges();

            if (result_aDZ_GoodsTemp.seq_id > 0)
            {
                strb.Append("操作成功");
                return new Tuple<bool, string, ADZ_GoodsTemp>(true, strb.ToString(), result_aDZ_GoodsTemp);
            }
            else
            {
                strb.Append("操作失败");
                return new Tuple<bool, string, ADZ_GoodsTemp>(false, strb.ToString(), result_aDZ_GoodsTemp);
            }
        }

        /// <summary>
        /// 单个商品上架
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Tuple<bool, string> toWithdraw(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            AddTempProductModel paramModel = new AddTempProductModel();
            if (id <= 0)
            {
                return new Tuple<bool, string>(false, $"传入的id错误id[{id}]");
            }

            var aDZ_GoodsTemp = dbcontext.ADZ_GoodsTemp.FirstOrDefault(t => t.seq_id == id && t.is_del == 0);
            if (aDZ_GoodsTemp == null)
            {
                return new Tuple<bool, string>(false, $"ADZ_GoodsTemp信息不存在id[{id}]");
            }


            paramModel = JsonHelper.Deserialize<AddTempProductModel>(aDZ_GoodsTemp.data_json);
            paramModel.aDZ_GoodsTemp = aDZ_GoodsTemp;
            //开始上架操作

            var aDZ_GoodsMaster = paramModel.aDZ_GoodsMaster;
            if (aDZ_GoodsMaster.brand_id <= 0 ||
                aDZ_GoodsMaster.category_id <= 0 ||
                aDZ_GoodsMaster.supplier_id <= 0 ||
                aDZ_GoodsMaster.material_source <=0 ||  //物料来源 leev
                paramModel.aDZ_GoodsLabel == null || paramModel.aDZ_GoodsLabel.label_type <= 0 ||
                string.IsNullOrWhiteSpace(aDZ_GoodsMaster.MPN)
                )
            {
                return new Tuple<bool, string>(false, $"品牌、分类、供应商、物料来源、料号等信息不完整id[{id}]");
            }
            if (aDZ_GoodsTemp.status == 0)
            {
                return new Tuple<bool, string>(false, $"此物料上传失败id[{id}]：{aDZ_GoodsTemp.remark}");
            }

            //添加主表
            aDZ_GoodsMaster.with_up_time = DateTime.Now;
            aDZ_GoodsMaster.is_withdraw = 0;
            aDZ_GoodsMaster.create_time = paramModel.aDZ_GoodsTemp.create_time;

            if (aDZ_GoodsMaster.min_amount <= 0)
                aDZ_GoodsMaster.min_amount = aDZ_GoodsMaster.stock_amount;
            aDZ_GoodsMaster.is_del = 0;
            aDZ_GoodsMaster = dbcontext.ADZ_GoodsMaster.Add(aDZ_GoodsMaster);
            dbcontext.SaveChanges();

            ///直播、预热、爆款上架需要更新标记
            var releaseListType = (ReleaseListType)paramModel.aDZ_GoodsLabel.label_type;            
            ReleaseBiz.Instance.SetNewReleaseNo(releaseListType);


            paramModel.aDZ_GoodsLabel.goods_id = aDZ_GoodsMaster.goods_id;
            paramModel.aDZ_GoodsLabel.is_show = 0;
            var aDZ_GoodsLabel = dbcontext.ADZ_GoodsLabel.Add(paramModel.aDZ_GoodsLabel);

            foreach (var img in paramModel.aDZ_GoodsIMGs)
            {
                img.goods_id = aDZ_GoodsMaster.goods_id;

                dbcontext.ADZ_GoodsIMG.Add(img);
            }

            //添加业务id绑定 daneel 20190421
            if (paramModel.aDZ_GoodsLabel.label_type == (int)LabelType.Jingjia)
            {
                dbcontext.ADZ_GoodsJingjia.Add(new ADZ_GoodsJingjia
                {
                    goods_id = aDZ_GoodsMaster.goods_id,
                    jingjia_id = paramModel.goodsBusinessModel.business_id.HasValue ? paramModel.goodsBusinessModel.business_id.Value : 0
                });
            }
            if (paramModel.aDZ_GoodsLabel.label_type == (int)LabelType.Huodong)
            {
                dbcontext.ADZ_GoodsHuodong.Add(new ADZ_GoodsHuodong
                {
                    goods_id = aDZ_GoodsMaster.goods_id,
                    huodong_id = paramModel.goodsBusinessModel.business_id.HasValue ? paramModel.goodsBusinessModel.business_id.Value : 0
                });
            }

            //删除记录
            aDZ_GoodsTemp.is_del = 1;

            int savedCount = dbcontext.SaveChanges();


            if (savedCount > 0)
            {
                return new Tuple<bool, string>(true, $"操作成功id[{id}]");
            }

            return new Tuple<bool, string>(false, $"操作失败id[{id}]");
        }

        /// <summary>
        /// 删除单个未上架商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Tuple<bool, string> Delete(long id = 0)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            AddTempProductModel paramModel = new AddTempProductModel();
            if (id <= 0)
            {
                return new Tuple<bool, string>(false, $"传入的id错误id[{id}]");
            }

            var aDZ_GoodsTemp = dbcontext.ADZ_GoodsTemp.FirstOrDefault(t => t.seq_id == id && t.is_del == 0);
            if (aDZ_GoodsTemp == null)
            {
                return new Tuple<bool, string>(false, $"ADZ_GoodsTemp信息不存在id[{id}]");
            }

            aDZ_GoodsTemp.is_del = 1;

            int savedCount = dbcontext.SaveChanges();
            return new Tuple<bool, string>(true, $"操作成功id[{id}]");

        }


        #region 供应商上传资料
        public Tuple<bool, string> SupplieraddMoreTempProduct(ADZ_GoodsTempFileSupplier paramModel)
        {
            StringBuilder strb = new StringBuilder();
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ///以下添加新图片
            HttpFileCollection hfc = HttpContext.Current.Request.Files;
            if (hfc != null && hfc.Count > 0)
            {
                bool needSave = true;
                for (int i = 0; i < hfc.Count; i++)
                {
                    needSave = true;
                    var file = hfc[i];
                    if (file == null || string.IsNullOrWhiteSpace(file.FileName))
                        continue;
                    try
                    {
                        var contentType = file.ContentType;
                        var len = file.ContentLength;

                        if (len > 1024 * 1024 * 100)
                        {
                            strb.Append($"_{file.FileName}上传文件大小只能在100M以下。");
                            continue;
                        }

                        var zip_temp_dir = ConfigHelper.AppSetting<string>("supplier_temp_dir", "~/upload/supplier");
                        zip_temp_dir = HttpContext.Current.Server.MapPath(zip_temp_dir);

                        string fileName = Path.Combine(paramModel.supplier_id.ToString(), file.FileName);

                        if (dbcontext.ADZ_GoodsTempFileSupplier.FirstOrDefault(t => (t.file_name == fileName) && t.status > 0) != null)
                        {
                            needSave = false;
                            strb.Append($"_{file.FileName}文件已经存在，如要上传请更换文件名。");
                        }

                        if (needSave)
                        {
                            string file_fullpath = Path.Combine(zip_temp_dir, fileName);
                            string file_dir = Path.GetDirectoryName(file_fullpath);
                            if (!Directory.Exists(file_dir))
                                Directory.CreateDirectory(file_dir);
                            try
                            {
                                file.SaveAs(file_fullpath);
                                dbcontext.ADZ_GoodsTempFileSupplier.Add(
                                    new ADZ_GoodsTempFileSupplier
                                    {
                                        supplier_id = paramModel.supplier_id,
                                        file_name = fileName,
                                        status = 1,
                                        remark = "文件上传成功",
                                        create_time = DateTime.Now,
                                        batch = paramModel.batch
                                    }
                                    );

                                //发送业务消息
                                BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                                {
                                    BusinessMsgType = (int)BusinessMsgEnum.SellersubmitGoods,
                                    msg = $"卖家上传物料，供应商名称【{dbcontext.ADZ_SupplierMaster.FirstOrDefault(t=>t.supplier_id== paramModel.supplier_id).supplier_name}】，文件名【{fileName}】",
                                    msg_title = "卖家上传物料",
                                    msg_url = $"/TempProduct/SupplierMoreTempProductList"
                                });

                            }
                            catch (Exception ex)
                            {
                                dbcontext.ADZ_GoodsTempFileSupplier.Add(
                                    new ADZ_GoodsTempFileSupplier
                                    {
                                        supplier_id = paramModel.supplier_id,
                                        file_name = fileName,
                                        status = 0,
                                        remark = "文件上传失败",
                                        create_time = DateTime.Now,
                                        batch = paramModel.batch
                                    }
                                    );
                            }
                            finally
                            {
                                dbcontext.SaveChanges();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        strb.Append($"_{file.FileName}异常:" + ex.GetExcetionMessage());
                    }
                }
            }
            if (strb.Length > 0)
                return new Tuple<bool, string>(false, strb.ToString());
            else
                return new Tuple<bool, string>(true, "文件上传成功");
        }
        #endregion

    }
}